<template>
  <div style="border-top: 1px solid #EBEEFD">
    <fieldTree
      :field-items="fieldItems"
      :default-expanded-keys="defaultExpandedKeys"
      :allow-drop="allowDrop"
      :allow-drag="allowDrag"
      :last-check-required="lastCheckRequired"
      :required-text="requiredText"
      :status-required="statusRequired"
      draggable
      @node-drop="handleDrop"
      @getData="getData" />
  </div>
</template>
<script>
import fieldTree from '@/components/SettingPage/fieldTree';
export default {
  name: 'OrderFormTree',
  components: { fieldTree },
  props: {
    requestApi: {
      type: Function,
      default: null
    },
    fieldItems: {
      type: Array,
      default: () => {
        return [];
      }
    },
    defaultExpandedKeys: {
      type: Array,
      default: () => {
        return [];
      }
    },
    lastCheckRequired: {
      type: Boolean,
      default: false
    },
    requiredText: {
      type: String,
      default: ''
    },
    statusRequired: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
    };
  },
  computed: {
    respetPid() {
      return this.fieldItems[0].pid;
    }
  },
  methods: {
    getData() {
      this.$emit('getData', [this.respetPid]);
    },
    async handleDrop(draggingNode, dropNode) {
      const params = {};
      params.id = draggingNode.data.id;
      params.parentId = dropNode.parent.data.id;
      params.leafLevel = dropNode.level - 1;
      params.moveToIndex = dropNode.parent.childNodes.findIndex(node => node.data.id === draggingNode.data.id);
      try {
        const res = await this.requestApi(params);
        res.code === 200 ? this.$message.success('排序成功') : this.getData();
      } catch (e) {
        this.getData();
      }
    },
    allowDrop(draggingNode, dropNode, type) {
      if (draggingNode.level === dropNode.level && dropNode.parent.data.item.filter(i => i.name === draggingNode.data.name).length) {
        // 向上拖拽 || 向下拖拽
        return type === 'prev' || type === 'next';
      } else {
        // 不同级进行处理
        return false;
      }
    },
    allowDrag(draggingNode) {
      return draggingNode.level > 1 && !draggingNode.data._isAdd;
    }
  }
};
</script>
